import { defineStore } from 'pinia';
import * as Cesium from 'cesium';
import Dialog from "@/utils/clickopen/dialog";
import { useScaleStore } from "@/stores/scaleStore";

export const useEddyStore = defineStore('eddy', {
  state: () => ({
    viewer: null, // Cesium Viewer 实例
    eddiesData: [], // 原始涡旋数据
    coldEddies: [], // 冷涡数据
    warmEddies: [], // 暖涡数据
    isColdVisible: false, // 冷涡显隐状态
    isWarmVisible: false, // 暖涡显隐状态
    eddyCollection: {
      coldPrimitives: [], // 冷涡Primitive
      warmPrimitives: [], // 暖涡Primitive
      coldEntities: [], // 冷涡Entity
      warmEntities: [], // 暖涡Entity
    },
    handler: null, // 事件处理器
    dialogs: null
  }),
  actions: {
    setViewer(viewer) {
      this.viewer = viewer;
    },
    
    // 设置涡旋数据并分类
    setEddiesData(eddiesData, type = null) {
      this.eddiesData = eddiesData;
      // 根据type参数决定加载全部还是特定类型
      if (type === 'cold') {
        this.coldEddies = eddiesData.filter(eddy => eddy.type === 'cyclonic');
      } else if (type === 'warm') {
        this.warmEddies = eddiesData.filter(eddy => eddy.type !== 'cyclonic');
      } else {
        this.coldEddies = eddiesData.filter(eddy => eddy.type === 'cyclonic');
        this.warmEddies = eddiesData.filter(eddy => eddy.type !== 'cyclonic');
      }
      // if (type === 'cold') {
      //   this.coldEddies = eddiesData.filter(eddy => eddy.eddy_type === 1);
      // } else if (type === 'warm') {
      //   this.warmEddies = eddiesData.filter(eddy => eddy.eddy_type !== 1);
      // } else {
      //   this.coldEddies = eddiesData.filter(eddy => eddy.eddy_type === 1);
      //   this.warmEddies = eddiesData.filter(eddy => eddy.eddy_type !== 1);
      // }
    },
    
    // 加载特定类型的涡旋
    loadEddy(type) {
      const eddies = type === 'cold' ? this.coldEddies : this.warmEddies;
      const color = type === 'cold' 
        ? Cesium.Color.BLUE.withAlpha(0.5) 
        : Cesium.Color.RED.withAlpha(0.5);
      
      eddies.forEach((eddy, index) => {
        // 生成唯一ID - 结合类型和索引
        const uniqueId = `${type}-${index}`;
        
        const positions = eddy.boundary.map((boundaryPoint) =>
          Cesium.Cartesian3.fromDegrees(boundaryPoint.lon, boundaryPoint.lat)
        );
    
        const geometryInstance = new Cesium.GeometryInstance({
          geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: new Cesium.PolygonHierarchy(positions),
            vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            extrudedHeight: 1000,
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
          },
          id: uniqueId  // 为几何实例也设置唯一ID
        });
    
        const primitives = new Cesium.Primitive({
          geometryInstances: geometryInstance,
          appearance: new Cesium.PerInstanceColorAppearance({
            closed: true,
            translucent: true,
          }),
        });
        primitives.eddyIndex = index;
        primitives.eddyType = type;
        this.viewer.scene.primitives.add(primitives);
        
        if (type === 'cold') {
          this.eddyCollection.coldPrimitives.push(primitives);
        } else {
          this.eddyCollection.warmPrimitives.push(primitives);
        }
    
        if (eddy.max_velocity) {
          const position = Cesium.Cartesian3.fromDegrees(
            eddy.center.lon,
            eddy.center.lat
          );
          const centerPoint = this.viewer.entities.add({
            position: position,
            point: {
              pixelSize: 8,
              color: type === 'cold' ? Cesium.Color.BLUE : Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 1,
            },
            id: uniqueId,  // 使用唯一ID
            eddyType: type
          });
          
          if (type === 'cold') {
            this.eddyCollection.coldEntities.push(centerPoint);
          } else {
            this.eddyCollection.warmEntities.push(centerPoint);
          }
        }
      });

      // 添加点击事件监听器
      if (!this.handler) {
        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.handler.setInputAction((click) => {
          const scaleStore = useScaleStore();
  const scale = scaleStore.currentScale || 1;
  
  // 反向计算坐标
  const adjustedPosition = new Cesium.Cartesian2(
    click.position.x / scale,
    click.position.y / scale
  );const pickedObject = this.viewer.scene.pick(adjustedPosition);
          // const pickedObject = this.viewer.scene.pick(click.position);
          const ray = this.viewer.camera.getPickRay(adjustedPosition);
          var cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
          
          if (Cesium.defined(pickedObject)) {
            if (pickedObject.primitive && pickedObject.primitive.eddyIndex !== undefined) {
              const eddyIndex = pickedObject.primitive.eddyIndex;
              const type = pickedObject.primitive.eddyType;
              const eddy = type === 'cold' ? this.coldEddies[eddyIndex] : this.warmEddies[eddyIndex];
              
              let displayType = type === 'cold' ? "冷涡(气旋涡旋)" : "暖涡(反气旋涡旋)";
              const opts = {
                viewer: this.viewer,
                position: { _value: cartesian },
                title: "涡旋信息",
                title1: "涡旋类型：",
                title2: "涡旋半径：",
                title3: "涡旋中心：",
                title4: "涡旋最大平均地转流速：",
                content: displayType,
                content2: eddy.radius_km.toFixed(3)+"km",
                content3: `${eddy.center.lon.toFixed(3)} ° E, ${eddy.center.lat.toFixed(3)} ° N`,
                content4: `${eddy.max_velocity.toFixed(3) } m/s`,
              };
              
              if (this.dialogs) {
                this.dialogs.windowClose();
              }
              this.dialogs = new Dialog(opts);
            } else if (pickedObject.id !== undefined && pickedObject.id.eddyType) {
              // const eddyIndex = pickedObject.id.id;
              // const type = pickedObject.id.eddyType;
              // const eddy = type === 'cold' ? this.coldEddies[eddyIndex] : this.warmEddies[eddyIndex];
              // alert(`Clicked on ${type === 'cold' ? '冷涡' : '暖涡'} Center\nRadius: ${eddy.radius_km}\nCenter: (${eddy.center.lat}, ${eddy.center.lon})`);
            }
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }
    },
    
    // 切换显隐状态
    toggleEddyVisibility(visible, type) {
      if (type === 'cold') {
        this.isColdVisible = visible;
      } else if (type === 'warm') {
        this.isWarmVisible = visible;
      }
      
      if (visible) {
        this.loadEddy(type);
      } else {
        this.clearEddies(type);
      }
    },
    
    // 清除特定类型的涡旋
    clearEddies(type) {
      if (type === 'cold') {
        this.eddyCollection.coldPrimitives.forEach(primitive => {
          this.viewer.scene.primitives.remove(primitive);
        });
        this.eddyCollection.coldEntities.forEach(entity => {
          this.viewer.entities.remove(entity);
        });
        this.eddyCollection.coldPrimitives = [];
        this.eddyCollection.coldEntities = [];
      } else if (type === 'warm') {
        this.eddyCollection.warmPrimitives.forEach(primitive => {
          this.viewer.scene.primitives.remove(primitive);
        });
        this.eddyCollection.warmEntities.forEach(entity => {
          this.viewer.entities.remove(entity);
        });
        this.eddyCollection.warmPrimitives = [];
        this.eddyCollection.warmEntities = [];
      }
      if (this.dialogs) {
        this.dialogs.windowClose();
      }
      // 如果都没有显示了，移除handler
      if (!this.isColdVisible && !this.isWarmVisible && this.handler) {
        this.handler.destroy();
        this.handler = null;
      }
    }
  },
});